
//优化排产

export default class ProductionSchedule {
    constructor(materials, machines, processes, tasks,strategy) {
        this.materials = materials;
        this.machines = machines;
        this.processes = processes;
        this.tasks = tasks;
        this.strategy = strategy;

        this.dp = null;
        this.processGraph = this.createProcessGraph();
    }

    // 初始化 dp 数组
    initDP() {
        this.dp = new Array(this.tasks.length + 1).fill(null).map(() => new Array(this.processes.length + 1).fill(0));
    }

    // 创建工序图，存储工序之间的依赖关系
    createProcessGraph() {
        let graph = {};
        for (let task of this.tasks) {
            for (let process of task.processes) {
                if (!graph[process]) graph[process] = [];
                graph[process].push(task);
            }
        }
        return graph;
    }

    // 计算最优排产计划
    computeOptimalSchedule() {
        this.initDP();

        for (let i = 1; i <= this.tasks.length; i++) {
            this.calculateMaxProduction(i);
        }

        return this.dp[this.tasks.length];
    }

    // 计算当前阶段的最大生产量
    calculateMaxProduction(i) {
        let maxProduction = 0;

        for (let j = 0; j < this.processes.length; j++) {
            if (this.isProcessReady(j, i)) {
                let production = this.dp[i - 1][j] + this.calculateProcessTime(j, i);
                maxProduction = Math.max(maxProduction, production);
            }
        }

        this.dp[i][this.processes.length] = maxProduction;
    }

    // 检查工序是否准备好
    isProcessReady(processIndex, taskIndex) {
        let task = this.tasks[taskIndex];
        let process = task.processes[processIndex];
        let machinesRequired = this.machines.filter(machine => machine.canProcess(process.material));

        return machinesRequired.some(machine => machine.isAvailable());
    }

    // 计算工序所需时间
    calculateProcessTime(processIndex, taskIndex) {
        let task = this.tasks[taskIndex];
        let process = task.processes[processIndex];
        let machine = this.machines.find(machine => machine.canProcess(process.material));
        let time = machine.process(process.material, process.time);

        return time;
    }
}

// 示例材料、机器、工序和任务
let materials = [/* 材料列表 */];
let machines = [/* 机器列表，包括 canProcess 和 process 方法 */];
let processes = [/* 工序列表，包括 material, time 等信息 */];
let tasks = [/* 任务列表，包括 processes 列表 */];

// 实例化 ProductionSchedule 对象
let productionSchedule = new ProductionSchedule(materials, machines, processes, tasks);

// 计算最佳排产方案
let result = productionSchedule.computeOptimalSchedule();
console.log("最佳生产量为：" + result);
